import { clone, indexForObjArr } from '@/utils/index'
import { getType, setType, removeType, setTypeId, getTypeId } from '@/utils/auth'
import { empty } from '@/utils/test';

const state = {
	goodsTypes: getType(),
	goodsTypeId: getTypeId()
}

const getters = {
	statusOk: (state, getters) => {
		const { goodsTypes } = state
		const res = []
		const len = goodsTypes.length
		for (let index = 0; index < len; index++) {
			const item = goodsTypes[index]
			const { status } = item
			if (status) res.push(item)
		}
		return clone(res)
	},
	findById: (state, getters) => (id) => {
		const { goodsTypes } = state
		if (empty(id)) return ''
		const i = indexForObjArr(goodsTypes, id, 'id')
		return i >= 0 ? clone(goodsTypes[i]) : ''
	},
	nameById: (state, getters) => (id) => {
		const { goodsTypes } = state
		if (empty(id)) return ''
		const i = indexForObjArr(goodsTypes, id, 'id')
		if (i < 0) return ''
		const { name } = goodsTypes[i]
		return name
	},
	/**
	 * @example 通过模块来获取产品类型
	 * @param {String} mode 模块 'goods', 'parts', 'repair', 'setup' all
	 * @returns {Array} 产品类型
	 */
	typeByMode: (state, getters) => (mode) => {
		const res = []
		if (!['goods', 'parts', 'repair', 'setup', 'declaration', 'all'].includes(mode)) return res
		const statusOk = getters.statusOk
		if (mode === 'all') return statusOk
		const length = statusOk.length
		for (let index = 0; index < length; index++) {
			const item = statusOk[index]
			const { mode: MODES } = item
			if (MODES.includes(mode)) res.push(item)
		}
		return res
	}
}

const mutations = {
	/**
	 * @example 产品类型数组
	 * @param {Array} data 产品类型数组
	 * @returns {} 无
	 */
	SET_INIT: (state, data) => {
		if (!Array.isArray(data)) return console.warn('产品类型非数组', data)
		const { id } = data[0]
		setType(data)
		setTypeId(id)
		state.goodsTypes.splice(0, Infinity, ...data)
		state.goodsTypeId = id
	},
	/**
	 * @example 缓存 TYPE_ID
	 * @param {Number} typeId 产品类型ID 
	 * @returns {} 无
	 */
	SET_TYPE_ID: (state, typeId) => {
		setTypeId(typeId)
		state.goodsTypeId = typeId
		return typeId
	},
}


const actions = {
	/**
	 * @example 根据模块来重新生成 缓存 TYPE_ID
	 * @param {String} mode 模块 'goods', 'parts', 'repair', 'setup' all
	 * @returns {} 无
	 */
	setTypeByMode: ({ state, commit, getters }, mode) => {
		if (!['goods', 'parts', 'repair', 'setup','declaration'].includes(mode)) return
		const type = getters.typeByMode(mode)
		if (empty(type)) return
		// 判断是否包括
		const isIn = type.some(({ id }) => {
			return id === state.goodsTypeId
		})
		if (isIn) return
		// 选择第一条类型ID
		const { id: firstTypeId } = type[0]
		commit('SET_TYPE_ID', firstTypeId)
		return firstTypeId
	},
}



export default {
	namespaced: true,
	state,
	getters,
	actions,
	mutations,
}